import NetGet as ng
import ParseWeb as pw


class MyError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

class ImgData:
    ImgName=''
    ImgContent=''
    ImgIntroduce=''
    ImgUrl=''

    def __init__(self,**kwargs):
        if 'ImgContent' in kwargs.keys():
            self.ImgContent=kwargs['ImgContent']
        if 'ImgName' in kwargs.keys():
            self.ImgName=kwargs['ImgName']
        if 'ImgIntroduce' in kwargs.keys():
            self.ImgIntroduce=kwargs['ImgIntroduce']
        if 'ImgUrl' in kwargs.keys():
            self.ImgUrl=kwargs['ImgUrl']

    def From_Web_Get_Content(self):
        if self.ImgUrl!='':
            try:
                self.ImgContent=ng.Picture_request(self.ImgUrl)
            except MyError as e:
                e.value="url有错误"
                print(e.value)
    def dot_replacement(self,domain_match):
        domain_name=pw.Domain_name(domain_match)
        try:
            if len(domain_name)==0:
                raise MyError("域名输入有错误")
            if (self.ImgUrl[0] == '.'):
                self.ImgUrl = domain_name[0] + self.ImgUrl[1:]

        except MyError as e:
            print( e.value)
    def Name_Complement(self):
        if self.ImgUrl != '':
            match_name = pw.herf_Name_match(self.ImgUrl, pw.Picture_suffix)
            self.ImgName = match_name[0][0] + '.' + match_name[0][1]
    def All_Complement(self):
        self.From_Web_Get_Content()
        self.Name_Complement()
    def Download(self,path:str):
        with open(path+"/"+self.ImgName, 'wb') as f:
            f.write(self.ImgContent)
    def AltToName_Complement(self):
        self.ImgName=self.ImgIntroduce




